﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Messaging;
using System.Text;

namespace OCR.Helper
{
    public class MyMessage
    {
        public MyMessage()
        {

        }
    }
    public class MyMSMQ
    {
        System.Collections.Concurrent.ConcurrentQueue<MyMessage> message=new System.Collections.Concurrent.ConcurrentQueue<MyMessage>();
        private void Test()
        {
            
        }
    }


    public class MSMQInstance
    {
        private static MSMQInstance instance = new MSMQInstance();
        private MessageQueue queue;

        public MessageQueue Queue
        {
            get { return queue; }
        }
        /// <summary>
        /// 后面改为读配置文件
        /// </summary>
        private string queuePath = ".\\private$\\TGCMAPPNotice";

        private MSMQInstance()
        {
            string value = ConfigurationSettings.AppSettings["TGCMAPP_MSMQ"].ToString();

            if (!string.IsNullOrEmpty(value))
            {
                queuePath = value;

                if (!MessageQueue.Exists(queuePath))
                {
                    //创建事务性队列，用于事务消息插入和读取
                    queue = MessageQueue.Create(queuePath, true);
                    queue.SetPermissions("Administrators", MessageQueueAccessRights.FullControl);
                    queue.Label = queuePath;
                    queue.DefaultPropertiesToSend.Priority = MessagePriority.Normal;
                }
                else
                {
                    queue = new MessageQueue(queuePath);

                }
            }
        }
        /// <summary>
        /// 单实例模式
        /// </summary>
        public static MSMQInstance Current
        {
            get
            {
                return instance;
            }
        }
    }
    //消息插入
    public class MSMQSend
    {
        /// <summary>
        /// 插入消息队列
        /// </summary>
        /// <param name="alias">推送别名</param>
        /// <param name="title">推送到客户端标题</param>
        /// <param name="alert">推送到客户端内容</param>
        /// <param name="priority">设置消息优先级</param>
        public void MSMQJPushJsonSend(HashSet<string> alias, string title, string alert, string obj, int type, string extra)
        {
            try
            {
                // PushPayload payload = SetPushValue(alias, title, alert, obj, type, extra);
                System.Messaging.Message message = new System.Messaging.Message();
                message.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                //   message.Body = payload.ToJson();

                MessageQueueTransaction mySend = new MessageQueueTransaction();
                mySend.Begin();
                MSMQInstance.Current.Queue.Send(message, mySend);
                mySend.Commit();
            }
            catch { }
            try
            {
                NoticeInstance notice = NoticeInstance.Current;
                notice.SendJPushMessage();
            }
            catch { }

        }
    }
    //消息读取及处理
    public class NoticeInstance
    {
        private static NoticeInstance instance = new NoticeInstance();
        //极光推送需要的app_key和密钥
        private String app_key = "c27e7beffd1fd4cb70749ce3";
        private String master_secret = "ad37ed4a475b099779b2cdd1";
        //  private static JPushClient client;

        private NoticeInstance()
        {
            //读取配置的极光推送的app_key和密钥
            app_key = ConfigurationSettings.AppSettings["QUERY_APP_KEY"].ToString();
            master_secret = ConfigurationSettings.AppSettings["QUERY_APP_MASTER_SECRET"].ToString();
            if (string.IsNullOrEmpty(app_key) || string.IsNullOrEmpty(master_secret))
            {
                throw new Exception("通知配置信息不全,QUERY_APP_KEY,QUERY_APP_MASTER_SECRET!");

            }
            else
            {
                //创建极光推送客户端
                //  client = new JPushClient(app_key, master_secret);
            }
        }
        /// <summary>
        /// 单实例模式
        /// </summary>
        public static NoticeInstance Current
        {
            get
            {
                return instance;
            }
        }
        /// <summary>
        /// 发送消息至极光推送
        /// </summary>
        /// <returns></returns>
        public void SendJPushMessage()
        {

            MSMQInstance.Current.Queue.PeekCompleted += new PeekCompletedEventHandler(Receive);
            MSMQInstance.Current.Queue.BeginPeek();
        }
        /// <summary>
        /// 从消息队列取消息以及发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Receive(object sender, PeekCompletedEventArgs e)
        {
            bool isSendSucceed = true;
            MessageQueueTransaction transaction = new MessageQueueTransaction();
            try
            {
                if (MSMQInstance.Current.Queue.Transactional)
                {
                    transaction.Begin();
                }

                //从消息队列获取消息，一直监听有新消息，才会执行
                System.Messaging.Message message = MSMQInstance.Current.Queue.EndPeek(e.AsyncResult);
                MSMQInstance.Current.Queue.Receive(transaction);
                message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });

                //调用极光推送API
                //初始化极光推送消息
                //string a = message.Body.ToString();
                //PushPayload payload = PushPayload.FromJSON(message.Body.ToString());

                //调用极光推送
            //    MessageResult result = client.SendPush(message.Body.ToString());
                if (MSMQInstance.Current.Queue.Transactional)
                {

                    transaction.Commit();
                }
            }
            catch (MessageQueueException)//消息队列读取异常
            {
                isSendSucceed = false;

                // 如果消息队列采用了事务并且出现了异常，则终止事务  
                if (MSMQInstance.Current.Queue.Transactional)
                {
                    transaction.Abort();
                  //  SupportWarnTimer swt = new SupportWarnTimer();
                   // swt.DueTimerStart();
                }
            }
            catch (Exception)//其它异常，有可能是极光推送异常
            {
                isSendSucceed = false;
                if (MSMQInstance.Current.Queue.Transactional)
                {
                    transaction.Abort();
                  //  SupportWarnTimer swt = new SupportWarnTimer();
                  //  swt.DueTimerStart();
                }
            }
            finally
            {
                if (isSendSucceed)
                {
                    //发送下一条
                    MSMQInstance.Current.Queue.BeginPeek();
                }
            }
        }
    }

}
